package com.usian.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.article.mapper.ApArticleConfigMapper;
import com.usian.article.mapper.ApArticleContentMapper;
import com.usian.article.mapper.ApArticleMapper;
import com.usian.article.service.ApArticleService;
import com.usian.model.article.dtos.ArticleHomeDto;
import com.usian.model.article.dtos.ArticleInfoDto;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.base.BaseServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.usian.common.contants.article.ArticleContants.*;

@Service
public class ApArticleServiceImpl extends BaseServiceImpl<ApArticleMapper,ApArticle> implements ApArticleService {
    @Autowired
    ApArticleConfigMapper configMapper;
    @Autowired
    ApArticleContentMapper contentMapper;

    private static final Integer maxSize = 50;

    @Override
    public ApArticleContent save(ApArticleContent content) {
        contentMapper.insert(content);
        return content;
    }

    @Override
    public ApArticleConfig save(ApArticleConfig config) {
        configMapper.insert(config);
        return config;
    }

    @Override
    public ResponseResult loadArticle(ArticleHomeDto dto, Short type) {
        if (dto==null)return errorParam;
        dto.setSize(Math.min(dto.getSize(),maxSize));
        if (type==null|| !type.equals(LOAD_MORE) || !type.equals(LOAD_NEW))type=LOAD_MORE;
        List<ApArticle> list = baseMapper.loadArticle(dto, type);
        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto articleInfoDto) {
        if (articleInfoDto==null||articleInfoDto.getArticleId()==null)return errorParam;
        ApArticleConfig config = configMapper.selectOne(Wrappers.<ApArticleConfig>lambdaQuery().eq(ApArticleConfig::getArticleId, articleInfoDto.getArticleId()));;
        Map<String,Object> map = new HashMap<>();
        if (!config.getIsDelete()||config.getIsDown()){
            ApArticleContent content = contentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, articleInfoDto.getArticleId()));;
            map.put("config",config);
            map.put("content",content);
            return ResponseResult.okResult(map);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"文章已删除或未上架");
    }
}
